package com.ants.common.utils;

import java.io.*;

import com.ants.common.exception.AntsException;
import com.aspose.words.*;

/**
 * TODO
 * Author Chen
 * Date   2023/12/20 9:39
 */
public class DocToPdfUtil {

    /**
     * 加载配置文件
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = DocToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * doc转pdf
     *
     * @param pdfPath pdf文件路径，包含.pdf
     * @description 如果流不为空则使用转pdf，反正则用docPath进行转pdf
     */
    public static File docToPdf(InputStream inputStream, String pdfPath) {
        System.out.println("pdf转换中...");
        long old = System.currentTimeMillis();

        File pdfFile = new File(pdfPath);
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            // 验证
            if (!getLicense()) {
                throw new AntsException("文件转换失败!");
            }

            Document document;
            if (inputStream != null) {
                document = new Document(inputStream);
            } else {
                throw new AntsException("文件转换失败!");
            }
            document.save(fos, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒");
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AntsException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String docPath = "F:\\出差审批单-陈爽.docx";
        String pdfPath = "F:\\出差审批单-陈爽.pdf";
        File pdf = DocToPdfUtil.docToPdf(null, pdfPath);

    }

}

